package com.common.www.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


/**
 * ehcache 缓存工具类
 * <p>
 * cacheName在ehcache.xml中配置
 */
public class CacheUtils {

    public static CacheManager manager = CacheManager.create();

    public static String CACHE_TOKEN = "token";

    public static Object get(String cacheName, Object key) {
        Cache cache = manager.getCache(cacheName);
        if (cache != null) {
            Element element = cache.get(key);
            if (element != null) {
                return element.getObjectValue();
            }
        }
        return null;
    }

    public static Cache getCache(String cacheName) {
        Cache cache = manager.getCache(cacheName);
        return cache;
    }

    public static void put(String cacheName, Object key, Object value) {
        Cache cache = manager.getCache(cacheName);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }

    public static boolean remove(String cacheName, Object key) {
        Cache cache = manager.getCache(cacheName);
        if (cache != null) {
            return cache.remove(key);
        }
        return false;
    }


    //以上为基本方法======================


    public static void putToken(String key, Object value) {
        removeToken(key);
        CacheUtils.put(CacheUtils.CACHE_TOKEN, key, value);
        Cache cache = manager.getCache(CacheUtils.CACHE_TOKEN);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }

    public static boolean removeToken(String userId) {
        Cache cache = manager.getCache(CacheUtils.CACHE_TOKEN);
        if (cache != null) {
            return cache.remove(userId);
        }
        return false;
    }


}